<template>
  <div class="task-book-list">
    <div class="page-header">
      <h2>任务书管理</h2>
      <el-button type="primary" @click="handleAdd" v-if="isTeacher">
        <el-icon><Plus /></el-icon>创建任务书
      </el-button>
    </div>

    <el-card>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="学生">
          <el-input v-model="searchForm.student_name" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="题目">
          <el-input v-model="searchForm.topic_title" placeholder="请输入题目关键词" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table :data="taskBooks" stripe v-loading="loading">
        <el-table-column prop="topicSelection.student.user.real_name" label="学生" />
        <el-table-column prop="topicSelection.thesisTopic.title" label="题目" show-overflow-tooltip />
        <el-table-column prop="topicSelection.thesisTopic.teacher.user.real_name" label="指导教师" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleView(row)">
                查看
              </el-button>
              <el-button 
                type="primary" 
                link 
                @click="handleEdit(row)"
                v-if="isTeacher && row.topicSelection.thesisTopic.teacher_id === currentUser.id"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                link 
                @click="handleDelete(row)"
                v-if="isTeacher && row.topicSelection.thesisTopic.teacher_id === currentUser.id"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 任务书表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '创建任务书' : '编辑任务书'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="选题" prop="selection_id" v-if="dialogType === 'add'">
          <el-select
            v-model="form.selection_id"
            placeholder="请选择选题"
            filterable
            remote
            :remote-method="searchSelections"
            :loading="selectionLoading"
          >
            <el-option
              v-for="selection in availableSelections"
              :key="selection.id"
              :label="selection.thesisTopic.title"
              :value="selection.id"
            >
              <div class="selection-option">
                <div>{{ selection.thesisTopic.title }}</div>
                <div class="selection-info">
                  <span>学生：{{ selection.student.user.real_name }}</span>
                  <span>指导教师：{{ selection.thesisTopic.teacher.user.real_name }}</span>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="研究内容" prop="research_content">
          <el-input
            v-model="form.research_content"
            type="textarea"
            :rows="4"
            placeholder="请输入研究内容"
          />
        </el-form-item>

        <el-form-item label="技术要求" prop="technical_requirements">
          <el-input
            v-model="form.technical_requirements"
            type="textarea"
            :rows="4"
            placeholder="请输入技术要求"
          />
        </el-form-item>

        <el-form-item label="进度安排" prop="schedule">
          <el-input
            v-model="form.schedule"
            type="textarea"
            :rows="4"
            placeholder="请输入进度安排"
          />
        </el-form-item>

        <el-form-item label="参考文献" prop="references">
          <el-input
            v-model="form.references"
            type="textarea"
            :rows="4"
            placeholder="请输入参考文献"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看任务书对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="任务书详情"
      width="800px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="学生">{{ currentTaskBook.topicSelection?.student?.user?.real_name }}</el-descriptions-item>
        <el-descriptions-item label="题目">{{ currentTaskBook.topicSelection?.thesisTopic?.title }}</el-descriptions-item>
        <el-descriptions-item label="指导教师">{{ currentTaskBook.topicSelection?.thesisTopic?.teacher?.user?.real_name }}</el-descriptions-item>
        <el-descriptions-item label="研究内容">{{ currentTaskBook.research_content }}</el-descriptions-item>
        <el-descriptions-item label="技术要求">{{ currentTaskBook.technical_requirements }}</el-descriptions-item>
        <el-descriptions-item label="进度安排">{{ currentTaskBook.schedule }}</el-descriptions-item>
        <el-descriptions-item label="参考文献">{{ currentTaskBook.references }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const selectionLoading = ref(false)
const dialogType = ref('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref(null)
const currentTaskBook = ref({})

const searchForm = reactive({
  student_name: '',
  topic_title: ''
})

const form = reactive({
  selection_id: '',
  research_content: '',
  technical_requirements: '',
  schedule: '',
  references: ''
})

const rules = {
  selection_id: [
    { required: true, message: '请选择选题', trigger: 'change' }
  ],
  research_content: [
    { required: true, message: '请输入研究内容', trigger: 'blur' }
  ],
  technical_requirements: [
    { required: true, message: '请输入技术要求', trigger: 'blur' }
  ],
  schedule: [
    { required: true, message: '请输入进度安排', trigger: 'blur' }
  ],
  references: [
    { required: true, message: '请输入参考文献', trigger: 'blur' }
  ]
}

const taskBooks = ref([])
const availableSelections = ref([])
const currentUser = computed(() => JSON.parse(localStorage.getItem('user') || '{}'))
const isTeacher = computed(() => currentUser.value.role === 'teacher')

const fetchTaskBooks = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: currentPage.value,
      per_page: pageSize.value,
      ...searchForm
    })
    const response = await fetch(`/api/task-books?${params}`)
    const data = await response.json()
    taskBooks.value = data.data
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取任务书列表失败')
  } finally {
    loading.value = false
  }
}

const searchSelections = async (query) => {
  if (query) {
    selectionLoading.value = true
    try {
      const response = await fetch(`/api/topic-selections?status=approved&student_name=${query}`)
      const data = await response.json()
      availableSelections.value = data.data
    } catch (error) {
      ElMessage.error('搜索选题失败')
    } finally {
      selectionLoading.value = false
    }
  } else {
    availableSelections.value = []
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchTaskBooks()
}

const resetSearch = () => {
  searchForm.student_name = ''
  searchForm.topic_title = ''
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTaskBooks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTaskBooks()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    selection_id: '',
    research_content: '',
    technical_requirements: '',
    schedule: '',
    references: ''
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  currentTaskBook.value = row
  viewDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该任务书吗？', '提示', {
      type: 'warning'
    })
    
    const response = await fetch(`/api/task-books/${row.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.ok) {
      ElMessage.success('删除成功')
      fetchTaskBooks()
    } else {
      const data = await response.json()
      ElMessage.error(data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const url = dialogType.value === 'add' 
      ? '/api/task-books'
      : `/api/task-books/${form.id}`
    
    const method = dialogType.value === 'add' ? 'POST' : 'PUT'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(form)
    })
    
    const data = await response.json()
    
    if (response.ok) {
      ElMessage.success(dialogType.value === 'add' ? '创建成功' : '更新成功')
      dialogVisible.value = false
      fetchTaskBooks()
    } else {
      ElMessage.error(data.message || (dialogType.value === 'add' ? '创建失败' : '更新失败'))
    }
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '创建失败' : '更新失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchTaskBooks()
})
</script>

<style scoped>
.task-book-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.selection-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.selection-info {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #909399;
}
</style> 